package com.stx.jeepay.merchant.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stx.jeepay.core.aop.MethodLog;
import com.stx.jeepay.core.entity.MchInfoEntity;
import com.stx.jeepay.core.entity.MchPayPassageEntity;
import com.stx.jeepay.core.entity.PayWayEntity;
import com.stx.jeepay.core.enums.ApiCodeEnum;
import com.stx.jeepay.core.enums.CS;
import com.stx.jeepay.core.model.ApiPageRes;
import com.stx.jeepay.core.model.ApiRes;
import com.stx.jeepay.core.service.MchInfoService;
import com.stx.jeepay.core.service.MchPayPassageService;
import com.stx.jeepay.core.service.PayWayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;

@Api(tags = "商户支付通道管理")
@RestController
@RequestMapping("/api/mch/payPassages")
public class MchPayPassageConfigController extends CommonCtrl {

    @Autowired
    private MchPayPassageService mchPayPassageService;

    @Autowired
    private PayWayService payWayService;

    @Autowired
    private MchInfoService mchInfoService;

    @ApiOperation("查询支付方式列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "pageNumber", value = "分页页码", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "分页条数", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "appId", value = "应用ID", required = true),
            @ApiImplicitParam(name = "wayCode", value = "支付方式代码"),
            @ApiImplicitParam(name = "wayName", value = "支付方式名称")
    })
    @PreAuthorize("hasAuthority('ENT_MCH_PAY_PASSAGE_LIST')")
    @GetMapping
    public ApiPageRes<PayWayEntity> list() {
        String appId = getValStringRequired("appId");
        String wayCode = getValString("wayCode");
        String wayName = getValString("wayName");

        LambdaQueryWrapper<PayWayEntity> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(wayCode)) {
            wrapper.eq(PayWayEntity::getWayCode, wayCode);
        }

        if (StringUtils.isNotBlank(wayName)) {
            wrapper.like(PayWayEntity::getWayName, wayName);
        }
        IPage<PayWayEntity> payWayPage = payWayService.page(getIPage(), wrapper);
        if (CollUtil.isNotEmpty(payWayPage.getRecords())) {
            // 支付方式代码集合
            List<String> wayCodeList = new LinkedList<>();
            payWayPage.getRecords().stream().forEach(payWayEntity -> wayCodeList.add(payWayEntity.getWayCode()));

            // 商户支付通道集合
            List<MchPayPassageEntity> mchPayPassageList = mchPayPassageService.list(new LambdaQueryWrapper<MchPayPassageEntity>()
                    .select(MchPayPassageEntity::getWayCode, MchPayPassageEntity::getState)
                    .eq(MchPayPassageEntity::getAppId, appId)
                    .eq(MchPayPassageEntity::getMchNo, getCurrentMchNo())
                    .in(MchPayPassageEntity::getWayCode, wayCodeList));
            for (PayWayEntity payWay : payWayPage.getRecords()) {
                payWay.addExt("passageState", CS.NO);
                for (MchPayPassageEntity mchPayPassage : mchPayPassageList) {
                    if (payWay.getWayCode().equals(mchPayPassage.getWayCode()) && mchPayPassage.getState() == CS.YES) {
                        payWay.addExt("passageState", CS.YES);
                        break;
                    }
                }
            }
        }
        return ApiPageRes.pages(payWayPage);
    }

    @ApiOperation("根据[应用ID]、[支付方式代码]查询可用的支付接口列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "appId", value = "应用ID", required = true),
            @ApiImplicitParam(name = "wayCode", value = "支付方式代码", required = true)
    })
    @PreAuthorize("hasAuthority('ENT_MCH_PAY_PASSAGE_CONFIG')")
    @GetMapping("/availablePayInterface/{appId}/{wayCode}")
    public ApiRes availablePayInterface(@PathVariable("appId") String appId, @PathVariable("wayCode") String wayCode) {
        String mchNo = getCurrentUser().getSysUser().getBelongInfoId();
        MchInfoEntity mchInfo = mchInfoService.getById(mchNo);
        if (mchInfo == null || mchInfo.getState() != CS.YES) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SELETE);
        }

        // 根据支付方式查询可用支付接口列表
        List<JSONObject> list = mchPayPassageService.selectAvailablePayInterfaceList(wayCode, appId, CS.INFO_TYPE_MCH_APP, mchInfo.getType());

        return ApiRes.ok(list);
    }

    @ApiOperation("商户支付通道详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "id", value = "支付通道ID", required = true)
    })
    @GetMapping("/{id}")
    public ApiRes detail(@PathVariable("id") Long id) {
        MchPayPassageEntity payPassage = mchPayPassageService.getById(id);

        if (payPassage == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SELETE);
        }
        if (!payPassage.getMchNo().equals(getCurrentUser().getSysUser().getBelongInfoId())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }
        payPassage.setRate(payPassage.getRate().multiply(new BigDecimal("100")));
        return ApiRes.ok(payPassage);
    }

    @ApiOperation("更新商户支付通道")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "reqParams", value = "商户支付通道配置信息", required = true)
    })
    @PreAuthorize("hasAuthority('ENT_MCH_PAY_PASSAGE_ADD')")
    @PostMapping
    @MethodLog(remark = "更新应用支付通道")
    public ApiRes saveOrUpdate() {
        String reqParams = getValStringRequired("reqParams");

        try {
            List<MchPayPassageEntity> mchPayPassageList = JSONArray.parseArray(reqParams, MchPayPassageEntity.class);
            mchPayPassageService.saveOrUpdateBatchSelf(mchPayPassageList, getCurrentMchNo());
            return ApiRes.ok();
        }catch (Exception e){
            return ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR);
        }
    }
}
